#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <unistd.h>
#include "Log.hpp"
#include "commd.hpp"
#include "nocopy.hpp"
using namespace std;

void Usage(const string& process) {
    cout << "Usage:\n\t" << process << " server_ip server_port\n" << endl;
}


int main(int argc, char* args[]) {
    if (argc != 3) {
        Usage(args[0]);
        return Usage_Erro;
    }
    string server_ip = args[1];
    uint16_t server_port = atoi(args[2]);

    // 1、创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        // 创建套接字失败
        cerr << "create socket error" << endl;
        exit(Socket_Err);
    }

    // 2、绑定。必须要绑定，但是不需要显示的绑定，客户端在第一次发消息的时候，系统会自动帮我们绑定
    // 填充服务端信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());


    string inbuffer;
    while (true) {
        // 先发消息
        cout << "Please# ";
        getline(cin, inbuffer);
        int n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server, sizeof server);
        if (n == -1) {
            break;
        }
        // 发送成功

        // 读取服务端返回
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof peer);
        socklen_t len = sizeof peer;
        char server_echo[1024];
        int m = recvfrom(sockfd, server_echo, sizeof(server_echo) - 1, 0, (struct sockaddr*)&peer, &len);
        if (m > 0) {
            server_echo[m] = '\0';
            cout << server_echo << endl;
        } else {
            break;
        }
    }
    close(sockfd);
    return 0;
}